<?php

/**
 * @var $submit Zend_Form_Element_Submit
 */
class Contest_Form_Theme extends Contest_Form_Abstract
{
    /**
	 *
	 * @var Core_Model_Share
	 */
	protected $_shareConfigRow = null;
    protected function _getShareConfigRow()
    {
        if(is_null($this->_shareConfigRow)){
            $this->_shareConfigRow = Core_Model_DbTable_Shares::getInstance()->getShareConfig($this->_contestRow->id);
        }
        return $this->_shareConfigRow;
    }

    protected function _validateMaxStringLength($label, $max = 255)
    {
        $maxLengthValidator = new Zend_Validate_StringLength(array('max' => $max));
		$maxLengthValidator->setMessage(
            sprintf(YouNet_Util::translate('ERROR_IS_TOO_LONG'), YouNet_Util::translate($label), $max), 
            Zend_Validate_StringLength::TOO_LONG
        );
		return $maxLengthValidator;
    }
    
	public function __construct(array $options = null)
	{
		if( !empty($options) && isset($options['contest']) )
		{
			if( $options['contest'] instanceof Core_Model_Contest)
			{
				$this->_contestRow = $options['contest'];
			}
		}
		parent::__construct();
	}

    protected function _initBegin()
	{
        $this->setAttrib('id', 'theme_setting');
	}

	protected  function _hasBackButton() {
		return true;
	}

	protected function _initFields()
	{
        $this->_fanGateSettings();
		$this->_themeSettings();
        $this->_sharedContentSettings();
        $this->_generalSettings();
	}
    
    private function _fanGateSettings(){
        $this->addElement('checkbox', 'is_need_to_like', array(
			'label'				=> '',
			'checkedValue'		=> Core_Model_Contest::NEED_LIKE_FANPAGE,
			'uncheckedValue'	=> Core_Model_Contest::DONT_NEED_LIKE_FANPAGE,
            'value'             => Core_Model_Contest::NEED_LIKE_FANPAGE,
            'description'       => 'BASIC_OPTION_NEED_TO_LIKE'
		));
		$this->is_need_to_like->getDecorator('Description')->setOptions(array('tag' => 'label', 'class' => '', 'for' => 'is_using_captcha'));
		$this->is_need_to_like->getDecorator('Description')->setOption('escape', false);
        
        $this->addElement(new YouNet_Form_Element_File('image_welcome',array(
            'decorators'	=> $this->_file_decorators,
            'label'			=> 'IMAGE_WELCOME',
            'class'         => 'length_longest'
        )));
        $this->image_welcome->setDestination(UPLOAD_PATH);
        $this->image_welcome->addValidator('Count', false, 1);
        $this->image_welcome->addValidator('Size', false, '1MB');
        $this->image_welcome->addValidator('Extension', false, 'jpg,png,gif,jpeg');
        $this->image_welcome->setDescription(sprintf(
            $this->getTranslator()->_('IMAGE_UPLOAD_FANPAGE_HINT'),
            '1MB',
            FANPAGE_MAX_WIDTH.'px'
        ));
        
        $this->addDisplayGroup(
            array(
                'is_need_to_like',
                'image_welcome'
            ), 
            'fan_gate_settings', 
            array(
                'legend' => 'THEME_HEADER_FAN_GATE_SETTINGS'
            )
        );
    }
    
    private function _themeSettings()
    {
        //--Image Banner
		$this->addElement(new YouNet_Form_Element_BannerImage('image_banner', array('class' =>'length_longest')));
		$this->image_banner->setDestination(UPLOAD_PATH);
		if( !empty($this->_contestRow) )
		{
			if( !empty($this->_contestRow->image_banner) )
			{
				$this->image_banner->setRequired(false);
			}
		}

		$this->addElement(new YouNet_Form_Element_BannerLink('banner_link', array('class' =>'length_longest')));

		//--Image Background
		$this->addElement(new YouNet_Form_Element_File('image_background',array(
			'decorators'	=> $this->_file_decorators,
			'label'			=> 'IMAGE_BACKGROUND',
            'class'         => 'length_longest'
		)));
		if( !empty($this->_contestRow) )
		{
			if( !empty($this->_contestRow->image_background) )
			{
				$this->image_background->setRequired(false);
			}
		}
		$this->image_background->setDestination(UPLOAD_PATH);
		$this->image_background->addValidator('Count', false, 1);
		$this->image_background->addValidator('Size', false, '1MB');
		$this->image_background->addValidator('Extension', false, 'jpg,png,gif,jpeg');
		$this->image_background->setDescription(sprintf(
			$this->getTranslator()->_('IMAGE_UPLOAD_FANPAGE_HINT'),
			'1MB',
			FANPAGE_MAX_WIDTH.'px'
		));
        
		$this->addElement(new YouNet_Form_Element_Css(null, array(
            'class' =>'length_longest', 
            'label' => 'LABEL_SKIN'
        )));
		$this->skin->setDestination(SKIN_PATH . '/template/');
        
        $this->addDisplayGroup(
            array(
                'image_banner',
                'banner_link',
                'image_background',
                'skin'
            ), 
            'theme_settings', 
            array(
                'legend' => 'THEME_HEADER_THEME_SETTINGS'
            )
        );
    }
    
    private function _sharedContentSettings()
    {
        $this->addElement('text', 'share_title', array(
			'label'		=> 'LABEL_SHARE_TITLE',
            'class'     => 'length_longest',
			'required'	=> true,
			'filters'	=> array('StringTrim')
		));
		$this->share_title->addValidator($this->_validateMaxStringLength('LABEL_SHARE_TITLE', 255));
        
        $this->addElement('radio', 'using_image', array(
            'label'         => 'LABEL_SHARE_IMAGE',
            'multiOptions'  =>array(
                Core_Model_DbTable_Shares::USING_BANNER_IMAGE => 'OPTION_USING_BANNER_IMAGE',
                Core_Model_DbTable_Shares::USING_UPLOAD_IMAGE => 'OPTION_USING_UPLOAD_IMAGE'
            ),
            'value'         => Core_Model_DbTable_Shares::USING_BANNER_IMAGE,
            'required'      => true
        ));
        
        $this->addElement(new YouNet_Form_Element_File('share_image',array(
            'decorators'	=> $this->_file_decorators,
            'label'			=> ''
        )));
        $this->share_image->setDestination(UPLOAD_PATH);
        $this->share_image->addValidator('Count', false, 1);
        $this->share_image->addValidator('Size', false, '204800');
        $this->share_image->addValidator('Extension', false, 'jpg,png,gif,jpeg');
        $this->share_image->setDescription(sprintf($this->getTranslator()->_('SHARED_IMAGE_UPLOAD_FANPAGE_HINT'), '200KB', '200x200px'));
        
        $this->addElement('textarea', 'share_description', array(
			'label'		=> 'LABEL_SHARE_DESCRIPTION',
            'class'     => 'length_longest',
			'rows'		=> '5',
			'required'	=> true
		));
        $this->share_description->addValidator($this->_validateMaxStringLength('LABEL_SHARE_DESCRIPTION', 1000));
        
        $this->addDisplayGroup(
            array(
                'share_title',
                'using_image',
                'share_image',
                'share_description'
            ), 
            'shared_content_settings', 
            array(
                'legend' => 'THEME_HEADER_SHARED_CONTENT_SETTINGS',
                'escape' => false
            )
        );
    }

    private function _generalSettings()
    {
        //Add google analytics ID
        $this->addElement(new YouNet_Form_Element_Ga(null, array(
            'class' => 'length_longest',
            'label'	=> "LABEL_GOOGLE_ANALYTICS_ID"
        )));
		$this->google_analytics_id->getDecorator('description')->setOptions(array('class' => 'hint'));
		
		$this->addElement(new YouNet_Form_Element_Moderators('notify_email', array(
            'class' => 'length_longest',
            'label'	=> "LABEL_NOTIFY_EMAIL"
        )));
		$this->notify_email->getDecorator('description')->setOptions(array('class' => 'hint'));
        
		$this->addElement('select', 'default_view', array(
			'label' => 'LABEL_CONTEST_TARGET',
            'class' => 'length_medium',
			'multioptions' => Core_Model_DbTable_Contests::getListView()
		));
		$this->addElement('select', 'default_sort', array(
			'label' => 'LABEL_CONTEST_SORT_DEFAULT',
            'class' => 'length_medium',
			'multioptions' => Core_Model_DbTable_Entries::getArrayViewTypes()
		));
        $this->default_sort->getDecorator('Label')->setOption('escape', false);
        
		$this->addElement(new YouNet_Form_Element_Language(null, array(
            'class' => 'length_short',
            'label'	=> "LABEL_CONTEST_LANGUAGE"
        )));
        
        $this->addDisplayGroup(
            array(
                'google_analytics_id',
                'notify_email',
                'default_view',
                'default_sort',
                'language'
            ), 
            'general_settings', 
            array(
                'legend' => 'THEME_HEADER_GENERAL_SETTINGS'
            )
        );
    }
    
    private function _updatePreviousImage(Core_Model_Contest $contestRow)
	{
		if( !empty($contestRow->image_banner) )
		{
			//-- Using desciption
			$description		= $this->image_banner->getDescription();
			
			$description		.= '<span>';
			$description		.= '<input type="hidden" name="is_delete_banner"/>';			
			$description		.= '<img src="'.$contestRow->getBannerImageUrl().'"/>';
			$description		.= '<span class="btn_delete">delete</span>';
			$description		.= '</span>';
			
			$this->image_banner->setDescription($description);
			$this->image_banner->getDecorator('Description')->setOption('escape',false);
		}

		if( !empty($contestRow->image_background) )
		{
			$description		= $this->image_background->getDescription();
			
			$description		.= '<span>';
			$description		.= '<input type="hidden" name="is_delete_background"/>';
			$description		.= '<img src="'.$contestRow->getBackgroundImageUrl().'"/>';
			$description		.= '<span class="btn_delete">delete</span>';
			$description		.= '</span>';
			
			$this->image_background->setDescription($description);
			$this->image_background->getDecorator('Description')->setOption('escape',false);
		}

		if( !empty($this->image_welcome) )
		{
			if( !empty($contestRow->image_welcome) )
			{
				$description		= $this->image_welcome->getDescription();
				
				$description		.= '<span>';
				$description		.= '<input type="hidden" name="is_delete_welcome"/>';
				$description		.= '<img src="'.$contestRow->getWelcomeImageUrl().'"/>';
				$description		.= '<span class="btn_delete">delete</span>';
				$description		.= '</span>';
				
				$this->image_welcome->setDescription($description);
				$this->image_welcome->getDecorator('Description')->setOption('escape',false);
			}
		}
        
        if( !empty($this->share_image) )
		{
            $shareRow = $this->_getShareConfigRow();
			if( !empty($shareRow->image) )
			{
				$description		= $this->share_image->getDescription();
				
				$description		.= '<span>';
				$description		.= '<input type="hidden" name="is_delete_share_image"/>';
				$description		.= '<img src="'.$shareRow->getImage().'"/>';
				$description		.= '<span class="btn_delete">delete</span>';
				$description		.= '</span>';
				
				$this->share_image->setDescription($description);
				$this->share_image->getDecorator('Description')->setOption('escape',false);
			}
		}
        
        if( !empty($this->skin) )
		{
            $description		= $this->skin->getDescription();
			if( !empty($contestRow->skin) )
			{
                $description		.= '<span>';
				$description		.= '<a href="'.Zend_Controller_Front::getInstance()->getBaseUrl() . '/contest/manage/downloadskindefault/id/'.$contestRow->id.'">'.$this->getTranslator()->_('THEME_DOWNLOAD_DEFAULT_CSS').'</a>';
				$description		.= '</span>';
                
				$description		.= '<span>';
				$description		.= '<input type="hidden" name="is_delete_skin"/>';
				$description		.= '<a href="'.$contestRow->getSkinHref().'">Skin</a>';
				$description		.= '<span class="btn_delete">delete</span>';
				$description		.= '</span>';

				
			}
            else{
                $description		.= '<span>';
				$description		.= '<a href="'.Zend_Controller_Front::getInstance()->getBaseUrl() . '/contest/manage/downloadskindefault/id/'.$contestRow->id.'">'.$this->getTranslator()->_('THEME_DOWNLOAD_DEFAULT_CSS').'</a>';
				$description		.= '</span>';
            }
            $this->skin->setDescription($description);
            $this->skin->getDecorator('Description')->setOption('escape',false);
		}
	}

	public function fill(Core_Model_Contest $contestRow)
	{
		$data				= $contestRow->toArray();		
		$this->populate($data);
        /*
         * Fill Share content into form
         */
        $shareRow = $this->_getShareConfigRow();
        $this->populate(array(
            'share_title' => $shareRow->title,
            'share_description' => $shareRow->description,
            'using_image' => $shareRow->using_image || Core_Model_DbTable_Shares::USING_BANNER_IMAGE
        ));
		return $this;
	}

	/**
	 * Get welcomeImage name
	 * The image is used when the use choose the option need to like the fanpage before join the contest
	 * @return string
	 */
	public function getImageWelcomeName()
	{
		return $this->_getImageNameAndReceive('image_welcome',FOLDER_WELCOME);
	}
    
    public function getImageShareName()
	{
		return $this->_getImageNameAndReceive('share_image',FOLDER_SHARE);
	}

	public function getImageBannerName()
	{
		return $this->_getImageNameAndReceive('image_banner',FOLDER_BANNER);
	}

	public function getImageBackgroundName()
	{
		return $this->_getImageNameAndReceive('image_background',FOLDER_BACKGROUND);
	}

	private function _getImageNameAndReceive($name, $subPath = null)
	{
		$ret_name			= '';
		/*@var $imageElement Zend_Form_Element_File*/
		$imageElement				= $this->$name;
		if( !empty($imageElement) )
		{
			$image_name			= $imageElement->getFileName(null, false);
			if ( !empty($image_name) )
			{
                $name_length = strlen($image_name);
				if($name_length  > 40 )
				{
					$image_name = substr($image_name, 0, 40) . substr($image_name, $name_length - 4, $name_length);
				}
					
				$ret_name	= time() . '_'. mt_rand(0, 9999).'_'. preg_replace('/[^A-Za-z0-9-_.]/', '', $image_name);
				$target		= UPLOAD_PATH;
				$thumnail	= UPLOAD_PATH.'/'.FOLDER_THUMBNAIL.'/';
				if( empty($subPath) )
				{
					$target		.= '/';					
				}
				else
				{
					$target		.= '/'.$subPath.'/';
				}
				$target		.= $ret_name;
				$thumnail	.= $ret_name;
				$imageElement->addFilter('Rename',array(
					'target'    => $target
				));
				if( $imageElement->receive() )
				{
					if( $name == 'image_banner')
					{
						$this->_cropImage($target, $thumnail);
					}
				}
			}
		}
		return $ret_name;
	}
	
	protected function _cropImage($source,$target)
	{
		Core_Util::createThumbnail($source,$target,Core_ImageUtil::DEFAULT_BANNER_THUMBNAIL_SIZE);
	}
    
    public function getCssSkinName()
	{
		return $this->_getCssNameAndReceive('skin');
	}

	private function _getCssNameAndReceive($name, $subPath = null)
	{
		$ret_name			= '';
		/*@var $fileElement Zend_Form_Element_File*/
		$fileElement				= $this->$name;
		if( !empty($fileElement) )
		{
			$file_name			= $fileElement->getFileName(null, false);
			if ( !empty($file_name) )
			{
                $name_length = strlen($file_name);
				if($name_length > 40 )
				{
					$file_name = substr($image_name, 0, 40) . substr($image_name, $name_length - 4, $name_length);
				}

				$ret_name	= time() . '_'. mt_rand(0, 9999).'_'. preg_replace('/[^A-Za-z0-9-_.]/', '', $file_name);
				$target		= TEMPLATE_PATH;
				if( empty($subPath) )
				{
					$target		.= '/';
				}
				else
				{
					$target		.= '/'.$subPath.'/';
				}
				$target	.= $ret_name;
				$fileElement->addFilter('Rename',array(
					'target'    => $target
				));
				$fileElement->receive();
			}
		}
		return $ret_name;
	}
	public function render(Zend_View_Interface $view = null)
	{
		if( !empty($this->_contestRow) )
		{
			$this->_updatePreviousImage($this->_contestRow);
		}
		/*
		 * remove button cancel and back
	     */
        $this->removeButton();
        $this->renameButton('submit', 'Save & Finished');
		return parent::render($view);
	}
	
	public function disableFields()
	{
	}
    
    public function isValid($data)
    {
        if($data['using_image'] == Core_Model_DbTable_Shares::USING_UPLOAD_IMAGE){
            $shareConfigRow = $this->_getShareConfigRow();
            if(empty($shareConfigRow->image) || !empty($data['is_delete_share_image'])){
                $this->share_image->setRequired(true);
            }
        }
        return parent::isValid($data);
    }
};